const Koa = require("koa");
const parser = require("koa-parser");
const router = require("koa-router")();
const cors = require("koa-cors"); // 允许跨域
const app = new Koa();

app.use(cors());
app.use(parser());
app.use(router.routes());

const fruitList = ["香蕉","苹果","鸭梨"];

// get方法：获取水果列表
router.get("/fruits",async ctx=>{
    ctx.body = fruitList;
})

// post方法：添加水果列表
router.post("/fruits",async ctx=>{
    let fruit = ctx.request.body.fruit;
    fruitList.push(fruit);
    ctx.body = true;
})

// delete方法：删除水果列表
router.delete("/fruits/:index",async ctx=>{
    let index = ctx.params.index;
    fruitList.splice(index,1);
    ctx.body = true;
})
router.put("/fruits/:index",async ctx=>{
    let index = ctx.params.index;
    let modFruit = ctx.request.body.fruit;
    fruitList[index] = modFruit;
    ctx.body = true;
})

app.listen(3000,()=>{
    console.log("server is running");
})